import java.util.Stack;

public class Solution143 {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public void reorderList(ListNode head) {
        int len=0;
        ListNode first=head;
        while(first!=null){
            len++;
            first=first.next;
        }
        int half=len%2==0?len/2:len/2+1;
        first=head;
        int c=0;
        while (c<half){
            first=first.next;
            c++;
        }
        Stack<ListNode> stack=new Stack<>();
        for (int i=0;i<len-half;i++){
            stack.push(first);
            first=first.next;
        }
        first=head;
        while (!stack.isEmpty()){
            ListNode temp=first.next;
            first.next=stack.pop();
            first.next.next=temp;
            if (stack.isEmpty()){
                temp.next=null;
            }
            first=temp;
        }
    }

    public static void main(String[] args) {
        ListNode listNode=new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4))));
        new Solution143().reorderList(listNode);
        System.out.println(listNode.val);
        System.out.println(listNode.next.val);
        System.out.println(listNode.next.next.val);
        System.out.println(listNode.next.next.next.val);
        System.out.println(listNode.next.next.next.next);
    }
}
